<template>
  <div class="app-container">


    <!-- vxe检索数据组件 -->
    <search-form
      ref="searchForm"
      :formSearchData.sync="formSearchData"

      @searchEventEmit="searchEventEmit"
      @resetSearchEventEmit="resetSearchEventEmit"
    >
    </search-form>


    <!-- 表格组件 -->
    <ex-base-table
      ref="exBaseTable"
      :tableColumn="tableColumn"
      :tableData="tableData"
      :loading.sync="loading"
      :isVxeColSeq="false"
      :isVxeToolbar="true"
      :isVxeCheckbox="true"
      :isVxeHandleS="true"
      @handleRemoveEmit="handleRemoveEmit"
      @handleCreateEmit="handleCreateEmit"
      @handleUpdateEmit="handleUpdateEmit"
      @handleRmoveColEmit="handleRmoveColEmit"
      @customSortMethodEmit="customSortMethodEmit"
    >
      <template v-slot:vxeToolsButtonsExtend>
        <el-button size="mini" icon="el-icon-s-data" @click="handleViewChart">生成曲线图</el-button>
      </template>

    </ex-base-table>

    <!-- 分页组件 -->
    <Pagination
      v-show="tablePage.totalResult>0"
      :total="tablePage.totalResult"
      :page.sync="tablePage.currentPage"
      :limit.sync="tablePage.pageSize"
      @pagination="pageFindList"
    />


    <!-- 表单提价组件 -->
    <submit-form
      ref="submitForm"
      :dialogFormVisible.sync="dialogFormVisible"
      :dialogStatus="dialogStatus"
      :formSubmitData.sync="formSubmitData"
      :curveDeadlineList="curveDeadlineList"
      :curveDeadlineSetList="curveDeadlineSetList"
      @handleFromUpdateDataEmit="handleFromUpdateDataEmit"
      @handleFromCreateDataEmit="handleFromCreateDataEmit"
      @resetFormDataEmit="resetFormSubmitData"
    >
    </submit-form>

    <!-- 曲线图 -->
    <el-dialog
      :title="chartTitle"
      :visible.sync="DialogChartVisible"
      append-to-body
    >
      <ExManyLineChart
        :chart-data="lineChartData"
      />
    </el-dialog>

  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// import PageHeaderLayout from '@/layouts/PageHeaderLayout'
// import ApeDrawer from '@/components/ApeDrawer'
// import { mapGetters } from 'vuex'
import XEUtils from 'xe-utils'
import * as _ from 'lodash'
// 基础折线图图表
import ExManyLineChart from '@/components/Echarts/LineChart/ExManyLineChart'
import {
  fetchLisTransfercurvezi,
  addtransfercurvezi,
  updatetransfercurvezi,
  deletetransfercurvezi,
  curveTermQueryTermScheme, //获取曲线期限列表
  curveTermQueryTermPrice,
} from './service/baseApi'
// 基础表格组件
import ExBaseTable from './components/ExBaseTable'
// 分页
import Pagination from '@/components/Pagination'
// 文章表单
import SubmitForm from './components/SubmitForm'
// 检索表单
import SearchForm from './components/SearchForm'
import resetFormSubmitData from '@/views/mixins/resetFormSubmitData'

export default {
  name: 'vxe-basetable',
  mixins:[resetFormSubmitData],
  components: {
    //PageHeaderLayout,
    ExBaseTable,
    Pagination,
    SubmitForm,
    SearchForm,
    ExManyLineChart
  },
  props: {
    /* 当前行数据 */
    currentRow: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  // 定义属性
  data() {
    return {
      // 检索条件
      formSearchData: {},
      // 排除条件
      sortField: '',
      sortFlag: '',

      /* 表单相关 */
      dialogFormVisible: false, // 修改删除弹出框
      dialogStatus: '',
      // 表单数据对象
      formSubmitData: {
        id: "",
        cv_name: "",
        curr_name: "",
        cv_type: "",
        s_date: '',
        e_date: "9999-12-31",
        tp_name: '',
        term_rate: [],
        remark: '',
        tp_id: '',
      },
      initFormSubmitData: {
        id: "",
        cv_name: "",
        curr_name: "",
        cv_type: "",
        s_date: '',
        e_date: "9999-12-31",
        tp_name: '',
        term_rate: [],
        remark: '',
        tp_id: '',
      },
      // 曲线期限 curveDeadlineList
      curveDeadlineList: [],
      // 曲线期限设置参数
      curveDeadlineSetList: [],
      /* 分页相关 */
      tablePage: {
        currentPage: 1, //当前页
        pageSize: 10,  // 每一页页数
        totalResult: 0
      },
      /* 表格相关 */
      tableColumn: [], // 表格字段
      loading: false, //表格loading特效
      tableData: [],  //表格数据

      /* 子表相关 */
      DialogSonTableVisible: false,

      /* 监听属性 watch API */
      debouncedGetDeadlineSetList: _.debounce(this.getDeadlineSetList, 500),

      /* 是否是更新DOM初始化操作 */
      isUpdateDOMInit: false,

      /* 曲线图 */
      chartTitle: '',
      DialogChartVisible: false,
      lineChartData: {
        tooltipFormatter: '',
        legendData: [],
        xAxisData: [],
        seriesData: []
      },
      lineChartColors: [
        '#5470c6',
        '#91cc75',
        '#fac858',
        '#ee6666',
        '#73c0de',
        '#3ba272',
        '#fc8452',
        '#9a60b4',
        '#ea7ccc'
      ],


    } //datareturn-end

  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {
    // 计算属性作为中间 使用watch层监听对象某个属性
    // 生效时间
    formSubmitDataSdate() {
      return this.formSubmitData.s_date
    },
    // 期限方案id
    formSubmitDataTpId() {
      return this.formSubmitData.tp_id
    },

  },
  // 监控data中的数据变化
  watch: {
    currentRow() {
      this.findList()
    },
    formSubmitDataSdate(newValue, oldValue) {
      this.debouncedGetDeadlineSetList()
    },
    formSubmitDataTpId(newValue, oldValue) {
      this.debouncedGetDeadlineSetList()
    },
  },
  // 方法集合
  methods: {

    getDeadlineSetList() {
      if (this.isUpdateDOMInit === false) {

        this.curveDeadlineSetList = []

        // 初始化-删除开头为"term_"的元素
        XEUtils.objectEach(this.formSubmitData, (item, key) => {
          if (key.startsWith("term_") && key !== 'term_rate') {
            // delete this.formSubmitData[`${key}`];
            this.$delete(this.formSubmitData,key)
          }
        })

        curveTermQueryTermPrice({
          m_id: this.formSubmitData.tp_id,
          // m_id: '8fa50871db694d688f0837c87ff879c1', /* TODO: 测试期限id */
          s_date: this.formSubmitData.s_date,
          // s_date: '2022-08-01', /* TODO: 测试生效日期 */
          e_date: this.formSubmitData.e_date
        }).then(({data}) => {
          this.curveDeadlineSetList = data
          // 初始化-增加开头为"term_"的元素
          // formSubmitDataCom[`term_${item.term_code}`]
          XEUtils.objectEach(data, (item, key) => {
            this.$set(this.formSubmitData, `term_${item.term_code}`, 0)
            // 一下写法不是响应式！！！不要用
            // this.formSubmitData[`term_${item.term_code}`] = item.rate
          })

        }, error => {

        })
      }
      // 重置-是否是更新DOM初始化操作
      this.isUpdateDOMInit = false
    },
    /* API数据操作相关 */
    // 查询数据
    findList() {
      this.loading = true
      // 请求表格数据
      fetchLisTransfercurvezi({

        commonpid: this.currentRow.id,

      }).then(({data}) => {
        // 给表格数据赋值
        this.tableData = data.rows
        // 给分页总数赋值
        this.tablePage.totalResult = data.total
        // 关闭加载特效
        setTimeout(() => {
          this.loading = false
        }, 0.5 * 1000)
      }, error => {
        // alert(error);
      })
    },

    pageFindList() {

      this.findList()
    },
    /* 表格组件相关 */
    // 初始化表格字段
    initTableCols() {
      const tabCols = [  //动态增加的字段 传进来的
        {field: 'cv_name', title: '曲线名称', width: 200},
        {field: 'curr_name', title: '币种', width: 200},
        {field: 'cv_typename', title: '拟合曲线方式', width: 200},
        {field: 's_date', title: '生效日期', width: 200},
        {field: 'e_date', title: '失效日期', width: 200},
        {field: 'tp_name', title: '期限方案', width: 200},
        {field: 'tp_id', title: '期限方案id', visible: false},
      ]
      this.tableColumn = tabCols;
    },
    // 重置表单内容
    resetFormSubmitData(obj = {}) {
      let newObj, resetObj, replaceObj, exclude
      // 没有重置对象默认重置所有值 isUndefined
      if (XEUtils.isUndefined(obj.resetObj) && XEUtils.isEmpty(obj.resetObj)) {
        resetObj = {
          id: '',
          cv_name: '', //曲线名称
          curr_name: '', //币种
          cv_type: '',
          s_date: '', //生效日期
          e_date: '', //失效日期
          tp_id: '', //期限方案id
        }
      } else {
        resetObj = obj.resetObj
      }

      // 替换（重置值）中的值：比如修改时需要回显的值
      replaceObj = obj.replaceObj || {}
      newObj = XEUtils.merge(resetObj, replaceObj)
      // 排除不重置的字段
      if (!XEUtils.isUndefined(obj.exclude) && !XEUtils.isEmpty(obj.exclude)) {
        exclude = obj.exclude
        XEUtils.arrayEach(exclude, (item, key) => {
          delete newObj[`${item}`];
        })
      }
      this.formSubmitData = XEUtils.merge(this.formSubmitData, newObj)
    },
    // 表格工具组-多选删除
    handleRemoveEmit(selectRecords) {

    },
    // 表格工具组-新增表单弹窗（需要表单组件）
    handleCreateEmit(type) {

      // 重置表单内容
      this.resetFormSubmitData({
        replaceObj: {
          cv_name: this.currentRow.cv_name, //曲线名称
          curr_name: this.currentRow.curr_name, //币种
          cv_type: this.currentRow.cv_typename, //
          e_date: '9999-12-31', //失效日期
        },
        exclude: [
          // 'curr_code'
        ]
      })
      this.dialogStatus = type
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.submitForm.$refs['dataForm'].clearValidate()
      })
    },
    // 行内按钮-修改数据弹窗（需要表单组件）
    handleUpdateEmit(row, type) {
      this.isUpdateDOMInit = true
      this.dialogStatus = type
      this.dialogFormVisible = true

      // alert(1)
      // 重置表单内容
      this.resetFormSubmitData({
        resetObj: Object.assign({}, row),
        // 重置数据值
        replaceObj: {
          cv_name: this.currentRow.cv_name, //曲线名称
          curr_name: this.currentRow.curr_name, //币种
          cv_type: this.currentRow.cv_typename, //

        },
        // exclude 排除不重置元素
        exclude: []
      })

      // 初试化-增加开头为"term_"的元素
      // formSubmitDataCom[`term_${item.term_code}`]
      XEUtils.objectEach(row.term_rate, (item, key) => {
        this.$set(this.formSubmitData, `term_${item.term_code}`, item.rate)
        // 一下写法不是响应式！！！不要用
        // this.formSubmitData[`term_${item.term_code}`] = item.rate
      })
      this.curveDeadlineSetList = row.term_rate
      this.$nextTick(() => {
        this.$refs.submitForm.$refs['dataForm'].clearValidate()
      })
    },
    // 单行删除
    handleRmoveColEmit(row) {
      // this.$refs.exBaseTable.$refs.xTable.remove(row)
      deletetransfercurvezi({
        tp_id: row.tp_id,
        m_id: row.m_id,
        s_date: row.s_date,
        e_date: row.e_date
      }).then(({data}) => {
        this.findList()
      }, error => {
        // alert(error);
      })
    },

    /* 表单组件相关 */
    // 更新
    handleFromUpdateDataEmit() {
      updatetransfercurvezi({
        ...this.formSubmitData,
        commonpid: this.currentRow.id,
        //检索条件
      }).then(({data}) => {

        this.findList()
        // 关闭加载特效

      }, error => {
        // alert(error);
      })
    },

    // 增加
    handleFromCreateDataEmit() {
      addtransfercurvezi({
        commonpid: this.currentRow.id,
        ...this.formSubmitData,  //检索条件
      }).then(({data}) => {

        this.findList()

      }, error => {
        // alert(error);
      })
    },

    /* 检索相关 */
    // 检索
    searchEventEmit() {
      this.tablePage.currentPage = 1
      this.findList()
    },
    // 重置
    resetSearchEventEmit() {
      // 重置代码...
      this.tablePage.currentPage = 1
      this.findList()
    },
    /* 排序 */
    customSortMethodEmit(property, order) {
      this.sortField = property
      this.sortFlag = order
      this.findList()

    },

    /* 子表格弹出 */
    viewSonTable(row) {
      this.DialogSonTableVisible = true
    },
    /* 获取曲线期限列表 */
    getCurveDeadlineList() {
      curveTermQueryTermScheme().then(({data}) => {
        this.curveDeadlineList = data
      }, error => {
        // alert(error);
      })
    },
    /* 生成图表 */
    handleViewChart() {

      let tooltipFormatter = `{b}<br />`
      let legendData = []
      let xAxisData = []
      let seriesData = []

      let xAxisArrAll = []
      // 获取选中数据
      let selectRecords = this.$refs.exBaseTable.$refs.xTable.getCheckboxRecords()
      console.log(selectRecords);
      if (selectRecords.length) {

        XEUtils.objectEach(selectRecords, (item, key) => {
          // 获取所有系列legendData
          legendData.push(`${item.tp_name}-${item.s_date}`)
          tooltipFormatter += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:${this.lineChartColors[`${key}`]}"></span>\
                	{a${key}}：{c${key}}%<br />`

          XEUtils.objectEach(item.term_rate, (val, key) => {
            // 累计所有X轴元素
            xAxisArrAll.push(val.term)
          })
        })

        // 去重获取X轴元素，获取显示X轴元素
        xAxisData = XEUtils.uniq(xAxisArrAll)
        // 重组所有选中数据
        XEUtils.objectEach(selectRecords, (item, key) => {
          let seriesDataData = []
          let termRateArr = {}

          XEUtils.objectEach(item.term_rate, (val, key) => {
            // 累计已知X轴元素数据
            termRateArr[`${val.term}`] = val.rate
          })
          console.log('termRateArr', termRateArr);
          // 按照完整的x轴元素 重组完整X轴元素数据
          XEUtils.objectEach(xAxisData, (val, i) => {
            let xVal = termRateArr[`${val}`] || 0
            seriesDataData.push(xVal)
          })
          console.log('seriesDataData', seriesDataData);

          seriesData.push({
            name: `${item.tp_name}-${item.s_date}`,
            type: 'line',
            smooth: true,
            data: seriesDataData
          })

        })


        console.log('seriesData', seriesData);
        console.log('tooltipFormatter', tooltipFormatter);

        this.lineChartData = {
          tooltipFormatter,
          legendData,
          xAxisData,
          seriesData
        }

        console.log('this.lineChartData', this.lineChartData);

        this.chartTitle = '曲线图'
        this.DialogChartVisible = true

      } else {
        this.$alert(this.$t('message.msg1'))
        return false;
      }

    },

  }, //method-end
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // 初始化表格字段
    this.initTableCols()
    // 初始化表格数据
    this.findList()
    // 获取曲线期限列表
    this.getCurveDeadlineList()

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  beforeCreate() {
  }, // 生命周期 - 创建之前
  beforeMount() {
  }, // 生命周期 - 挂载之前
  beforeUpdate() {
  }, // 生命周期 - 更新之前
  updated() {
  }, // 生命周期 - 更新之后
  beforeDestroy() {
  }, // 生命周期 - 销毁之前
  destroyed() {
  }, // 生命周期 - 销毁完成
  activated() {
  }, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>


.my-dropdown4 {
  width: 600px;
  height: 300px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
}
</style>